package com.sharemarking.application.common.controller;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.sharemarking.application.common.repository.UserRepo;

@Controller
@RequestMapping("pwd")
public class PwdController {
	
	@Autowired
	private UserRepo mr;
	
	@RequestMapping(value="resetPwd",method=RequestMethod.GET)
	public void resetPwd(){
	}
	
	/*@RequestMapping(value="resetPwd",method=RequestMethod.POST)
	public String resetPwd(String loginName,String validateCode,HttpSession session) throws Exception{
		boolean valid=ms.checkResetPwdMail(loginName, validateCode);
		if(!valid)return "redirect:resetPwd?error";
		session.setAttribute("resetPwd", loginName);
		return "redirect:newPwd";
	}*/
	
	/*@RequestMapping(value="sendValidateCode",method=RequestMethod.POST)
	@ResponseBody
	public void sendValidateCode(String loginName){
		ms.sendResetPwdMail(mr.findByLoginName(loginName));
	}*/
	
	@RequestMapping(value="newPwd",method=RequestMethod.GET)
	public void newPwdGet(){
		
	}
	
	@RequestMapping(value="newPwd",method=RequestMethod.POST)
	@Transactional
	public String newPwdPost(String newPwd,HttpSession session,RedirectAttributes redirectAttributes) throws NoSuchAlgorithmException{
		String loginName=(String)session.getAttribute("resetPwd");
		System.out.println(loginName);
		if(!StringUtils.isEmpty(loginName)){
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(newPwd.getBytes());
			String pwd = new BigInteger(1,md.digest()).toString(16);
			mr.findByLoginName(loginName).setPassword(pwd);
		}
		redirectAttributes.addFlashAttribute("valid", !StringUtils.isEmpty(loginName));
		return "redirect:result";
	}
	
	@RequestMapping(value="result",method=RequestMethod.GET)
	public void result(){
		
	}
}
